import { getMaterialCategory } from '../../../../api/index'

Component({
  properties: {
    show: {
      type: Boolean,
      value: false
    }
  },
  data: {
    list: [],
    columns: [
      {
        values: [],
      },
      {
        values: [],
      }
    ],
    currentValues: []
  },
  methods: {
    async change ({ detail: { index, value } }) {
      if (index === 0) {
        await this.getCategory(value[0].value, 1)
        let cKey = `currentValues[${index}]`
        this.setData({ [cKey]: value[0] })
      } else {
        this.setData({ currentValues: value })
      }
      console.log(this.data.currentValues)
    },
    confirm () {
      this.triggerEvent('change', this.data.currentValues)
    },
    close () {
      this.triggerEvent('close')
    },
    async getCategory (id = 0, index = 0) {
      try {
        const { ResultSet } = await getMaterialCategory({ parentId: id })
        let key = `columns[${index}].values`
        this.setData({
          [key]: ResultSet.userData.data
        })
        if (index === 1) {
          let cKey = `currentValues[1]`
          this.setData({ [cKey]: ResultSet.userData.data[0] })
        }
      } catch (err) {
        wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
      }
    },
    async beforeOpen () {
      this.setData({ columns: [{ values: [] }, { values: [] }] })
      await this.getCategory()
      await this.getCategory(this.data.columns[0].values[0].value, 1)
      let currentValues = [this.data.columns[0].values[0], this.data.columns[1].values[0]]
      this.setData({ currentValues })
    }
  },
})